﻿using System;
using System.Collections.Generic;
using System.Data;
using QQZiFramework;
using QQZiFramework.Membership;
using System.Threading.Tasks;
using System.Collections;
using QQZiFramework.MQ;

namespace DemoConsole
{
    class Program
    {
        static string hashKey = "OracleTest_Time";
        /// <summary>
        /// 服务周期性执行
        /// </summary>
        static void oracleTest(DBContext context)
        {
            DBContext rtContext, sourceContext;

            rtContext = OEMMemberShip.GetInstance("OracleTest").CreateDBContext();
            sourceContext = OEMMemberShip.GetInstance("OracleTest").CreateDBContext();

            List<LiveItem> lst1 = rtContext.QueryMany<LiveItem>(new { });
            var redisAccess = context.GetRedisDatabase();
            redisAccess.DeleteRedisItem(hashKey);
            foreach (var item in lst1)
            {
                redisAccess.SetHashItem(hashKey, item.TAGNAME, item.DATETIME.Ticks);
            }


            string sourceQuerySql = "select * from LIVE_SOURCE";
            List<LiveItem> lst = sourceContext.QueryManySql<LiveItem>(sourceQuerySql);
            sourceContext.Close();
            List<LiveItem> insertLst = new List<LiveItem>();
            List<LiveItem> updateLst = new List<LiveItem>();

            foreach (var item in lst)
            {
                long lastTimeTs = redisAccess.GetHashItem<long>(hashKey, item.TAGNAME, false);
                if (lastTimeTs > 0)
                {
                    if (lastTimeTs != item.DATETIME.Ticks && Math.Abs(lastTimeTs - item.DATETIME.Ticks) > 9999999)//差异到秒(1Ticks = 0.0001毫秒)
                    {
                        //有新数据，更新
                        updateLst.Add(item);
                        redisAccess.SetHashItem(hashKey, item.TAGNAME, item.DATETIME.Ticks);
                    }
                }
                else
                {
                    //没有则插入
                    insertLst.Add(item);
                    redisAccess.SetHashItem(hashKey, item.TAGNAME, item.DATETIME.Ticks);
                }
            }
            if (insertLst.Count > 0)
            {
                rtContext.DoBulkInsert(insertLst);
            }
            if (updateLst.Count > 0)
            {
                rtContext.DoBulkUpdate(updateLst);

            }
            rtContext.Close();
            context.LogMessage($@"更新{insertLst.Count + updateLst.Count}行");
        }
        static void MySqlTest()
        {
            var mysqlContext = OEMProgram.CreateDBContext("MYSQLTEST");
            mysqlContext.GetBusiness<MembershipBLL>().GetUserPermissions(1, LoginPlatfromId.Admin);
            // var sln = "a0d46a94d4b34501b205eab83070a1b7";
            // mysqlContext.Exists<ShopCategory>(new { Name__Custom = QQZiFramework.WhereItem_Custom.Create("$field = {0} or name ={0}", sln) });

            // //OEMMemberShip.GetInstance("MYSQLTEST").CreateDBContext();
            // // Console.WriteLine(mysqlContext.GetBusiness<TestBusiness>().SayHello());
            // // // var dt = mysqlContext.QueryTable("SELECT 'API_EG_JGXQS' tagname,now() datetime,`count` value FROM yiwu_ecgs_test");
            // // // Console.WriteLine(dt.Rows.Count);
            // // Console.WriteLine(mysqlContext.GetDBAccess().IsTableExists("amis_sln_definition"));
            // // Console.WriteLine(mysqlContext.GetDBAccess().IsColumnExists("bpm_biz_maintains", "id"));
            // // Console.WriteLine(mysqlContext.GetDBAccess().IsColumnExists("bpm_biz_maintains", "id2"));
            // // var arr = mysqlContext.GetDBAccess().GetTablePrimaryKeys("bpm_biz_maintains");
            // // Console.WriteLine(arr);

            // // mysqlContext.QueryMany<ShopCategory>(new { NameLike = "店铺" }, "ShopCategories", null);
            // // // mysqlContext.QueryMany<ShopCategory>(new { Id = "1" });
            // // var lst = mysqlContext.QueryMany<ShopCategory>(new { IdBetween = "0|100", Name = "店铺" }, "ShopCategories", null);//, CreateTime = "2020-01-01|2022-02-02"
            // // lst = mysqlContext.QueryMany<ShopCategory>(new { IdBetween = "1|50", Name = "店铺2" }, "ShopCategories", null);//, CreateTime = "2020-01-01|2022-02-02"
            // var lst = mysqlContext.QueryMany<ShopCategory>(new { IdIn = "0,1,2,3" }, "ShopCategories", null);//, CreateTime = "2020-01-01|2022-02-02"
            // lst = mysqlContext.QueryMany<ShopCategory>(new { IdIn = "0,1,2,3,4,5,100" }, "ShopCategories", null);//, CreateTime = "2020-01-01|2022-02-02"
            // mysqlContext.QueryMany<ShopCategory>(new { groupby = 1, Id__Custom = WhereItem_Custom.Create("in (1,3,4)") }, "ShopCategories", "IndexShow");
            // mysqlContext.QueryMany<ShopCategory>(new { groupby = 1, Id__Custom = WhereItem_Custom.Create("in (1,3,4,5,6,7)") }, "ShopCategories", "IndexShow");
            // mysqlContext.QueryMany<ShopCategory>(new { groupby = 1, Id__Custom = WhereItem_Custom.Create(">{0} and not in (1,2,3)") }, "ShopCategories", "IndexShow");

            // lst = mysqlContext.QueryTree<ShopCategory>("ShopCategories", new { }, "id");
            mysqlContext.FormatDataSource =new Hashtable();
            mysqlContext.FormatDataSource.Add("loginUserId",1);

            mysqlContext.QueryMany<NewsItem>(new { ClsCode = "{loginUserId}" }, "Public-News-Cls", null);
            mysqlContext.QueryMany<NewsItem>(new { ClsCode = "123" }, "Public-News-Cls-2", null);

            // mysqlContext.Close();
            QueryParam queryParamUserOrg = new QueryParam()
            {
                permission = "Public-News-Cls",
                queryField = "*",
                orderBy = "CreateTime desc"
            };
            queryParamUserOrg.WhereLike("Title", "隐私").WhereEq("Id", 8).WhereIn("ClsCode", new string[] { "sys" });
            //.WhereEq("GroupByClsCode",1);

            queryParamUserOrg.Page = new Pagger { PageIndex = 1, PageSize = 100 };
            var result1 = mysqlContext.QueryMany<NewsItem>(queryParamUserOrg);
            queryParamUserOrg.ClientWhere.Clear();
            queryParamUserOrg.orderBy = null;
            queryParamUserOrg.Page = null;

            queryParamUserOrg.AddWhere("Title__LIKE", "隐私").GrouBy("ClsCode");
            result1 = mysqlContext.QueryMany<NewsItem>(queryParamUserOrg);

            queryParamUserOrg.ClientWhere.Clear();
            queryParamUserOrg.AddWhere("Title__LIKE", "隐私").WhereNotEq("SortIndex", 100).AddWhere("Id__Between", "0|100"); ;
            result1 = mysqlContext.QueryMany<NewsItem>(queryParamUserOrg);


            queryParamUserOrg.ClientWhere.Clear();
            queryParamUserOrg.WhereBetween("Id", 0, 200);
            result1 = mysqlContext.QueryMany<NewsItem>(queryParamUserOrg);

            queryParamUserOrg.ClientWhere.Clear();
            queryParamUserOrg.WhereBetween("Id", 0, null);
            result1 = mysqlContext.QueryMany<NewsItem>(queryParamUserOrg);

            queryParamUserOrg.ClientWhere.Clear();
            queryParamUserOrg.WhereBetween("Id", null, 200);
            result1 = mysqlContext.QueryMany<NewsItem>(queryParamUserOrg);

            queryParamUserOrg.ClientWhere.Clear();
            queryParamUserOrg.WhereLt("Id", 200).WhereBetween("CreateTime", new DateTime(2022, 01, 01), DateTime.Now);
            result1 = mysqlContext.QueryMany<NewsItem>(queryParamUserOrg);

            mysqlContext.Exists<ShopCategory>(new { Id = 9 });
            mysqlContext.Count<NewsItem>(new { Id__Custom = WhereItem_Custom.Create("> {0}", "1") });
            mysqlContext.SetArgument("name", "main");
            DBContext context2 = mysqlContext.Membership.CreateDBContext();
            context2.SetArgument("name", "child");
            context2.SetArgument("mainContext", mysqlContext);
            mysqlContext.SetArgument("context2", context2);
            var result = mysqlContext.PartQuery("*", "amis_sln_definition", "id > 0", "id", 1, 100);
            mysqlContext.Close();
            mysqlContext.Dispose();


        }
        static void PostgreSQLTest()
        {
            var pgSQLContext = OEMMemberShip.GetInstance("PGSQLTEST").CreateDBContext();
            var dt = pgSQLContext.QueryTable("SELECT * from  yiwu_ecgs_test");
            Console.WriteLine(dt.Rows.Count);
        }

        static async void MQTest()
        {
            using (DBContext context = OEMProgram.CreateDBContext("MYSQLTEST"))
            {

                var aa = OEMProgram.GetMQAccess();
                var bb = OEMProgram.GetMQAccess();
                // try
                // {                
                //     aa.Publish("TestTopic.mygroup", "hello ");
                // }
                // catch(Exception ex){
                //     context.LogException(ex);
                //     return;
                // }

                aa.BindReceived("TestTopic_colys.mygroup", data =>
                {
                    Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId + "," + System.Text.Encoding.UTF8.GetString(data));
                    System.Threading.Thread.Sleep(50);
                    return true;
                });

                await Task.Factory.StartNew((object obj) =>
                     {
                         for (int i = 0; i < 1000000; i++)
                         {
                             ((IMQDriver)obj).Publish("TestTopic_colys.mygroup", "hello :" + i);
                             if (i % 30 == 0)
                                 System.Threading.Thread.Sleep(1000);
                         }
                     }, bb);
            }
        }


        [DBTable(TableName = "Live")]
        public class LiveItem : IDBEntity
        {
            [DBField(Usage = DBFieldUsage.PrimaryKey, Identity = false)]
            public string TAGNAME { get; set; }
            public DateTime DATETIME { get; set; }
            public float VALUE { get; set; }
        }

        private static void TestHttpAsync(DBContext context)
        {
            DateTime startTime = DateTime.Now;
            int finish = 0;
            int err = 0;
            int size = 300;
            int temp = 0;
            Task.Factory.StartNew(() =>
               {
                   while (finish < size)
                   {
                       double ss = (DateTime.Now - startTime).TotalSeconds;
                       if (temp != finish)
                       {
                           Console.WriteLine("完成" + finish + "，错误：" + err + "，用时" + ss + "秒，平均每个" + Math.Round(finish / ss, 2) + "秒！");
                           temp = finish;
                       }

                       System.Threading.Thread.Sleep(3000);
                   }

               });
            System.Net.ServicePointManager.DefaultConnectionLimit = 100;
            //使用异步请求
            for (int i = 0; i < size; i++)
            {
                var http = context.NewHttpUtility();
                http.DoPostAsync("http://localhost:5100/shm/home/TestWait?s=10", null, null, null, (code, html) =>
                 {
                     if (code == -1) err++;
                     finish++;

                 });
            }
            Console.WriteLine("异步请示全部发出，等待返回...");


        }

        public static void TestEmptyEntitySave(DBContext context)
        {

            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("Name", "name1");
            data.Add("Value", 100.98);
            data.Add("CreateTime", DateTime.Now);
            EmptyEntity empty = EmptyEntity.CreateIncrForSave("Table_1", "PK", null, data);
            //保存
            context.DoSave(empty);
            //更改
            data["Value"] = "200.09";
            empty = EmptyEntity.CreateIncrForSave("Table_1", "PK", empty.Id, data);
            context.DoSave(empty);

        }

        private static void TestRedis()
        {
            DateTime starTime = DateTime.Now;
            using (DBContext context = OEMProgram.CreateDBContext("JPAAS"))
            {
                context.GetRedisDatabase(1);

                // RedisAccess.Subscribe("test-subscribe", str =>
                // {
                //     Console.WriteLine(str);
                // });
                #region test pub subscribe
                // while (true)
                // {
                //     Console.WriteLine("please input cmd");
                //     string readStr = Console.ReadLine();
                //     if (readStr == "exit") return;
                //     try
                //     {
                //         RedisAccess.Publish("test-subscribe", readStr);
                //     }
                //     catch (Exception ex)
                //     {
                //         Console.WriteLine(ex.Message);
                //     }
                // }
                #endregion

                // #region test online/offline get
                // context.GetRedisDatabase(0).SetHashItem("test","1", "redis value is test");
                // while (true)
                // {
                //     Console.WriteLine("please input ");
                //     string readStr = Console.ReadLine();
                //     if (readStr == "exit") return;
                //     try
                //     {
                //         Console.WriteLine("get from redis:" + context.GetRedisDatabase(0).GetHashItem<string>("test","1"));
                //     }
                //     catch (Exception ex)
                //     {
                //         Console.WriteLine(ex.Message);
                //     }
                // }
                // #endregion


                // context.GetRedisDatabase(1).AddSortedSetItem<string>("sssss", 12, "21212");
                // context.GetRedisDatabase(1).AddSortedSetItem<string>("sssss", 20, "xx");
                // context.GetRedisDatabase(1).AddSortedSetItem<string>("sssss", 1, "212412");
                // Hashtable ht = context.GetRedisDatabase(1).SortedSetScan<string>("sssss");
                // Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(ht));

                // var setAll = context.GetRedisDatabase(1).CollectionGetALL<string>("p_user_roles:1");
                // context.GetRedisDatabase().CollectionAdd("colys_test_set", setAll);
                // long len = context.GetRedisDatabase(1).CollectionLength("colys_test_set");
                // if(len > 0)
                //     context.GetRedisDatabase().CollectionRemove("colys_test_set", setAll[0]);
                //Hashtable ht=   context.GetRedisDatabase(5).HashFind<string>("INDICATOR_CHANNEL_14", "*",100000);
                Task[] tasks = new Task[50];
                for (var i = 0; i < tasks.Length; i++)
                {
                    context.GetRedisDatabase(0).SetRedisItem("test" + i, i);
                    context.GetRedisDatabase(0).SetHashItem("hash-test", "test" + i, i);
                    tasks[i] = Task.Factory.StartNew((object obj) =>
                    {
                        try
                        {
                            for (int dbInde = 0; dbInde < 10; dbInde++)
                            {
                                for (int j = 0; j < 100; j++)
                                {
                                    context.GetRedisDatabase(dbInde).GetRedisItem<string>("test" + j, false);
                                    context.GetRedisDatabase(dbInde).GetHashItem<string>("hash-test", "test" + j, false);
                                    // if (val != null) Console.Write(val);

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }, context.OEM.Name);
                }
                Task.WaitAll(tasks);
                Console.WriteLine("OK:" + (DateTime.Now - starTime).TotalSeconds);

            }
            while (loop-- > 1)
            {
                TestRedis();
            }
        }
        static int loop = 50;

        static void Main(string[] args)
        {
            int workerThreadsMax;
            int completionPortThreadsMax;
            System.Threading.ThreadPool.GetMinThreads(out workerThreadsMax, out completionPortThreadsMax);
            System.Threading.ThreadPool.SetMinThreads(1000, completionPortThreadsMax);
            // using (DBContext context = OEMProgram.CreateDBContext("YIWU-WSMP"))
            // {
            //     QueryParam queryParam = new QueryParam { entityType = typeof(ObjectInfo), queryField = "*", Page = new Pagger { PageIndex = 1, PageSize = 10 } };
            //     queryParam.WhereGt("OBJECT_ID", 1);
            //     queryParam.Page.PageIndex++;
            //     var dt = context.DoQuery(queryParam);
            //     var obj = context.ExecScalar<ObjectInfo>("WSMP-INDICATOR-LIST", "OBJECT_NAME", new { OBJECT_ID = "1" }, null);
            //     var obj2 = context.ExecScalar<ObjectInfo>("WSMP-INDICATOR-LIST", "OBJECT_NAME", new { OBJECT_NAME = obj }, null);
            //     int cc= context.Count<ObjectInfo>(new { OBJECT_ID__Gt = "1" });
            //     dt = context.QueryTable<ObjectInfo>(new { OBJECT_NAME__like = "'+seklselse @123424234+'"},null,null);
            // }
            // dosamething();
            MySqlTest();
            // MQTest();
            // TestRedis();
            // string json ="{\"CreateTime\":1669827600000}";
            // ShopCategory category = Newtonsoft.Json.JsonConvert.DeserializeObject<ShopCategory>(json);
            // MQTest();
            return;


        }

        private static void dosamething()
        {
            using (DBContext context = OEMProgram.CreateDBContext("YIWU"))
            {

                var tables = context.GetDBAccess().GetTables();
                var keys = context.GetDBAccess().GetTableForeignKeys("ws_maintain_gsgd");
                // MQTest(context);
                // return;

                // var resultJson =context.NewHttpUtility().DoGet("http://10.193.80.116:5000/shaxian/WSMP/SelectObjectListByObjectType?object_type=FACTORY");
                TestEmptyEntitySave(context);


                //TestHttpAsync(context);

                var b = context.GetDBAccess().IsColumnExists("A1_Configs", "Id");

                var arr = context.GetDBAccess().GetTablePrimaryKeys("A1_Configs");
                //分页查询测试
                QueryParam queryParam = new QueryParam { entityType = typeof(ShopCategory), queryField = "*", Page = new Pagger { PageIndex = 1, PageSize = 10 } };
                queryParam.AddWhere("Id", "> 0");
                //context.DoQuery(queryParam);
                queryParam.Page.PageIndex++;
                context.DoQuery(queryParam);
                Console.WriteLine(queryParam.Page.Total.ToString());

                var category = context.QuerySingle<ShopCategory>(34);
                var aa = new ShopCategory() { Id = 10000 };
                aa.ParentId = IDBEntity.DefaultNullValue;
                context.Update(aa, "ParentId");
                // var users = context.QueryManySql<BaseUser>("select top 1 * from dbo.A0_Users where mobile ='13000000000'");
                // context.DoBulkInsert(users);
                // users[0].Name += "_Update";
                // context.DoBulkUpdate(users,"Name,CreateTime");
                //MQTest();
                //PostgreSQLTest();

                // var category = context.QuerySingle<ShopCategory>(34);
                category.ParentId = 53;
                context.Update(category, "ParentId", true);
                // Console.WriteLine( QQZiFramework.Utility.ConvertToInt26(24268));
                //     Console.WriteLine( QQZiFramework.Utility.ConvertToInt26(24468));



                //Newtonsoft.Json.Linq.JToken JToken = Newtonsoft.Json.Linq.JToken.Parse("{\"hello\":{val:\"----asdfsf\"}}");
                //string str=   QQZiFramework.Utility.FormatTemplate("asfsadf{hello.val}",JToken);
                // #region 登录测试
                //                 BaseUser u= context.Membership.GetRedisUser(1,context);
                //                 TokenInfo tokenInfo = context.Membership.SetUserLoginState(u,LoginUserStateType.Redis,DateTime.Now.AddDays(1),LoginPlatfromId.App,null,context);
                //                  context.Membership.GetTokenInfo(context);
                //                 //context.GetTokenInfo(); 
                //                 #endregion



                Console.Read();
                return;


                //                // List<IndicatorInfoEx> lst = context.QueryMany<IndicatorInfoEx>(new { OBJECT_TYPE = "pressureObjectTypeName", INDICATOR_TYPE = "PRESSURE" }, "WSMP-INDICATOR-LIST", "Scada_Object_Id");

                //    #region 订阅发布测试
                //  RedisAccess.Subscribe("test",x=>{
                //      Console.Write(x);
                //  });
                //  RedisAccess.Subscribe("test2",x=>{
                //      Console.WriteLine(x);
                //  });

                //  for (int i = 0; i < 20; i++)
                //  {
                //      if(i%5 ==0){
                //      RedisAccess.Publish("test2",i);    
                //      }else{
                //      RedisAccess.Publish("test",i);
                //      }

                //  }
                //   #endregion

                //              #region  微信测试
                //               var bll =WxAccessTokenDriver.Create(context,WxAccessWhich.MPAuth);
                //               context.SetArgument("access_token","40_e8tTmGjcKLsFFZdFqjZ06oewdqR_pqeBacapUEPkWOCTuSqsHWsueA69P1V_z6NhJwcMxfjVcwRhvBG_tnFFPCaMbNjkGcKx1WwSl7P3cMo");
                //               bll.GetUserInfo("ovC_Sw-3Qi9OOooLgCDD8fIkYP6k",WxSetting.OAuthScopeType.snsapi_userinfo);
                // #endregion


            }
        }


    }

}
